package com.jhj.provider.bm.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhj.provider.bm.client.ResumeClient;
import com.jhj.provider.bm.po.b.model.BmOrder;
import com.jhj.provider.bm.po.b.model.Imgs;
import com.jhj.provider.bm.po.b.model.OrderContract;
import com.jhj.provider.bm.po.b.model.OrderLog;
import com.jhj.provider.bm.po.b.model.Sale;
import com.jhj.provider.bm.service.BmOrderService;
import com.jhj.provider.bm.service.ImgService;
import com.jhj.provider.bm.service.OrderContractService;
import com.jhj.provider.bm.service.OrderLogService;
import com.jhj.provider.bm.service.SaleService;
import com.jhj.provider.bm.utils.Constants;
import com.jhj.provider.bm.vo.OrderContractVo;
import com.jhj.utils.AppResultData;
import com.jhj.utils.ImgServerUtil;
import com.jhj.utils.TimeStampUtil;
import com.jhj.utils.sign.JhjSignConfig;
import com.jhj.utils.sign.JhjSignUtils;

@RestController
public class OrderContractController {

	@Autowired
	private OrderContractService orderContractService;

	@Autowired
	private BmOrderService orderService;

	@Autowired
	private SaleService saleService;

	@Autowired
	private OrderLogService orderLogService;

	@Autowired
	private ImgService imgService;

	@Value("${img.host}")
	private String imgHost;

	@Autowired
	private ResumeClient resumeClient;

	/***
	 * 保存合同
	 * 
	 * @param orderId
	 *            订单id
	 * @param orderNo
	 *            订单号
	 * @param saleId
	 *            销售老师
	 * @param resumeId
	 *            人才库id
	 * @param mobile
	 *            手机号
	 * @param name
	 *            姓名
	 * @param idCard
	 *            身份证
	 * @param orderPay
	 *            支付金额
	 * 
	 */
	@RequestMapping(value = "/api/bm/order/contract/add.json", method = RequestMethod.POST)
	public AppResultData<Object> add(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id,
			@RequestParam(value = "orderId") Integer orderId, @RequestParam(value = "orderNo") String orderNo,
			@RequestParam(value = "resumeId", required = false) Integer resumeId,
			@RequestParam(value = "resumeNo", required = false) String resumeNo,
			@RequestParam(value = "resumeMobile") String resumeMobile,
			@RequestParam(value = "resumeName") String resumeName, @RequestParam(value = "idCard") String idCard,
			@RequestParam(value = "orderPay") BigDecimal orderPay,
			@RequestParam(value = "addr", required = false, defaultValue = "") String addr,
			@RequestParam(value = "contractDay", required = false, defaultValue = "") String contractDay,
			@RequestParam(value = "remark", required = false, defaultValue = "") String remark,
			@RequestParam(value = "actionId", required = false, defaultValue = "0") Integer actionId,
			@RequestParam(value = "actionName", required = false, defaultValue = "") String actionName,
			@RequestParam(value = "actionMobile", required = false, defaultValue = "") String actionMobile,
			@RequestParam(value = "orderFee", required = false, defaultValue = "0") BigDecimal orderFee,
			@RequestParam(value = "salary", required = false, defaultValue = "0") BigDecimal salary,
			@RequestParam(value = "contractEnd", required = false, defaultValue = "0") Integer contractEnd,
			@RequestParam(value = "fromDate", required = false, defaultValue = "") String fromDate,
			@RequestParam(value = "toDate", required = false, defaultValue = "") String toDate) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		BmOrder order = orderService.selectByPrimaryKey(orderId);

		if (order == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("订单信息不存在");
			return result;
		}

		
		Integer saleId = order.getSaleId();
		Sale sale = saleService.selectByPrimaryKey(saleId);

		Long t = TimeStampUtil.getMillisOfDay(contractDay) / 1000;
		Integer contractTime = t.intValue();

		OrderContract orderContract = new OrderContract();
		orderContract.setId(0);
		orderContract.setOrderId(orderId);
		orderContract.setOrderNo(orderNo);
		orderContract.setSaleId(saleId);
		orderContract.setConcatTime(contractTime);
		orderContract.setResumeId(resumeId);
		orderContract.setResumeNo(resumeNo);
		orderContract.setResumeMobile(resumeMobile);
		orderContract.setResumeName(resumeName);
		orderContract.setIdCard(idCard);
		orderContract.setOrderPay(orderPay);
		orderContract.setAddr(addr);
		orderContract.setRemark(remark);
		orderContract.setSalary(salary);
		orderContract.setOrderFee(orderFee);
		orderContract.setAddTime(TimeStampUtil.getNowSecond().intValue());
		orderContract.setOrderFee(orderFee);
		orderContract.setStatus(1);
		
		//判断时间
		    int res = fromDate.compareTo(toDate);
			    if(res>0)
			    {
			    	result.setStatus(Constants.ERROR_999);
					result.setMsg("开始时间大于结束时间");
					return result;
			    }else{
			    	orderContract.setFromDate(fromDate);
			    	orderContract.setToDate(toDate);
			    	
			    }
			    
		orderContractService.insert(orderContract);

		// 更新订单状态
		order.setOrderId(orderId);
		order.setOrderStatus(Constants.ORDER_STATUS_4);
		order.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
		orderService.update(order);

		// 更新销售老师销售总金额和级别
		BigDecimal totalSale = sale.getTotalSale();
		totalSale = totalSale.add(orderPay);
		sale.setTotalSale(totalSale);
		int level = saleService.getSaleLevel(saleId);
		sale.setLevel(level);
		saleService.update(sale);

		// 记录日志
		OrderLog log1 = new OrderLog();
		log1.setOrderId(orderId);
		log1.setOrderNo(orderNo);
		log1.setLogType("order_contract");
		log1.setLogName("订单签约");
		log1.setActionId(actionId);
		log1.setActionName(actionName);
		log1.setRemark("订单签约,登记合同信息");
		log1.setAddTime(TimeStampUtil.getNowSecond().intValue());
		orderLogService.insert(log1);

		// 更新orderResume表

		// 更新jhj-provider-resume 的状态
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("resumeNo", resumeNo);
		params.put("status", "0");
		params.put("actionId", String.valueOf(actionId));
		params.put("actionName", actionName);
		params.put("actionMobile", actionMobile);
		params = JhjSignUtils.getSignParams(params);

		String appkey = JhjSignConfig.appkey;
		String oncestr = params.get("oncestr").toString();
		String sign = params.get("sign").toString();

		resumeClient.setStatus(resumeNo, 0, actionId, actionName, actionMobile, appkey, oncestr, sign);
		Integer contractId = orderContract.getId();
		result.setData(contractId);
		return result;
	}

	/**
	 * 
	 * @param id
	 * @param orderId
	 * @param orderNo
	 * @param imgs
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/api/bm/order/contract/upload.json", method = RequestMethod.POST)
	public AppResultData<Object> upload(@RequestParam(value = "orderId") Integer orderId,
			@RequestParam(value = "orderNo") String orderNo, @RequestParam(value = "contractId") Integer contractId,
			@RequestParam(value = "imgs", required = false) MultipartFile[] imgs)
			throws JsonParseException, JsonMappingException, IOException {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		// 处理上传图片
		for (int i = 0; i < imgs.length; i++) {
			String url = imgHost + "/upload/";
			String fileName = imgs[i].getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
			fileType = fileType.toLowerCase();
			String sendResult = ImgServerUtil.sendPostBytes(url, imgs[i].getBytes(), fileType);

			ObjectMapper mapper = new ObjectMapper();
			HashMap<String, Object> o = mapper.readValue(sendResult, HashMap.class);
			// String ret = o.get("ret").toString();
			HashMap<String, String> info = (HashMap<String, String>) o.get("info");
			String imgUrl = imgHost + "/" + info.get("md5").toString();

			Imgs record = imgService.initPo(new Imgs());
			record.setImgType(Constants.IMG_TYPE_ORDER_CONTRACT);
			record.setImgUrl(imgUrl);
			record.setOrderId(orderId);
			record.setOrderNo(orderNo);
			record.setLinkId(contractId);
			record.setAddTime(TimeStampUtil.getNowSecond().intValue());
			imgService.insert(record);
		}

		return result;
	}

	/**
	 * 合同详情
	 * 
	 * @param orderId
	 *            订单id
	 * @return OrderContractVo
	 * 
	 * 
	 */
	@RequestMapping(value = "/api/bm/order/contract/get.json", method = RequestMethod.GET)
	public AppResultData<Object> getOrderContract(@RequestParam(value = "orderId") Integer orderId,
			@RequestParam(value = "status") Integer status) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		BmOrder order = orderService.selectByPrimaryKey(orderId);

		if (order == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("订单信息不存在");
			return result;
		}

		OrderContract o = new OrderContract();
		o.setOrderId(orderId);
		o.setStatus(status);
		OrderContract orderContract = orderContractService.selectOne(o);

		if (orderContract == null)
			orderContract = orderContractService.initPo(new OrderContract());

		OrderContractVo vo = orderContractService.getVo(orderContract, order);
		result.setData(vo);
		return result;
	}

	/**
	 * 无效的合同记录
	 * 
	 * @param orderNo
	 *            订单编号
	 * @return list
	 * 
	 */
	@RequestMapping(value = "/api/bm/order/contract/getListByStatus.json", method = RequestMethod.GET)
	public AppResultData<Object> getOrderContract(@RequestParam(value = "orderNo") String orderNo) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		OrderContract ot = new OrderContract();
		ot.setOrderNo(orderNo);
		//ot.setStatus(0);
		List<OrderContract> list = orderContractService.selectBySearchVo(ot, "add_time desc");
		result.setData(list);
		return result;
	}

	/**
	 * 变更合同
	 * 
	 * 
	 * 
	 * */
	@RequestMapping(value = "/api/bm/order/contract/change.json", method = RequestMethod.POST)
	public AppResultData<Object> changeContract(
			@RequestParam(value = "id", required = false, defaultValue = "0") Integer id,
			@RequestParam(value = "orderId") Integer orderId, 
			@RequestParam(value = "orderNo") String orderNo,
			@RequestParam(value = "resumeId", required = false) Integer resumeId,
			@RequestParam(value = "resumeNo", required = false) String resumeNo,
			@RequestParam(value = "resumeMobile") String resumeMobile,
			@RequestParam(value = "resumeName") String resumeName, 
			@RequestParam(value = "idCard") String idCard,
			@RequestParam(value = "orderPay") BigDecimal orderPay,
			@RequestParam(value = "addr", required = false, defaultValue = "") String addr,
			@RequestParam(value = "contractDay", required = false, defaultValue = "") String contractDay,
			@RequestParam(value = "remark", required = false, defaultValue = "") String remark,
			@RequestParam(value = "actionId", required = false, defaultValue = "0") Integer actionId,
			@RequestParam(value = "actionName", required = false, defaultValue = "") String actionName,
			@RequestParam(value = "actionMobile", required = false, defaultValue = "") String actionMobile,
			@RequestParam(value = "orderFee", required = false, defaultValue = "0") BigDecimal orderFee,
			@RequestParam(value = "salary", required = false, defaultValue = "0") BigDecimal salary,
			@RequestParam(value = "contractEnd", required = false, defaultValue = "0") Integer contractEnd,
			@RequestParam(value = "saleId", required = false, defaultValue = "0") Integer saleId,
			@RequestParam(value = "fromDate", required = false, defaultValue = "") String fromDate,
			@RequestParam(value = "toDate", required = false, defaultValue = "") String toDate) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		OrderContract oc = new OrderContract();
		oc.setOrderId(orderId);
		List<OrderContract> orderContractList = orderContractService.selectBySearchVo(oc, "add_time desc");
		if (orderContractList.isEmpty()) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("合同信息不存在，请添加合同");
			return result;
		}else {
			for(int i=0;i<orderContractList.size();i++) {
				OrderContract contract = orderContractList.get(i);
				if(contract.getStatus()==1) {
					contract.setStatus(0);
					orderContractService.update(contract);
				}
			}
		}

//		Integer saleId = order.getSaleId();
//		Sale sale = saleService.selectByPrimaryKey(saleId);
//		
		Long t = TimeStampUtil.getMillisOfDay(contractDay) /1000;
		Integer contractTime = t.intValue();

		OrderContract orderContract = new OrderContract();
		orderContract.setOrderId(orderId);
		orderContract.setOrderNo(orderNo);
		orderContract.setSaleId(saleId);
		orderContract.setConcatTime(contractTime);
		orderContract.setResumeId(resumeId);
		orderContract.setResumeNo(resumeNo);
		orderContract.setResumeMobile(resumeMobile);
		orderContract.setResumeName(resumeName);
		orderContract.setIdCard(idCard);
		orderContract.setOrderPay(orderPay);
		orderContract.setAddr(addr);
		orderContract.setRemark(remark);
		orderContract.setAddTime(TimeStampUtil.getNowSecond().intValue());
		orderContract.setOrderFee(orderFee);
		orderContract.setSalary(salary);
		orderContract.setStatus(1);
		orderContract.setFromDate(fromDate);
		orderContract.setToDate(toDate);
		orderContract.setContractEnd(contractEnd);
		orderContractService.insert(orderContract);

		// 更新订单状态
		BmOrder order = new BmOrder();
		order.setOrderId(orderId);
		order.setOrderStatus(Constants.ORDER_STATUS_4);
		order.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
		orderService.update(order);

		//更新上一个销售老师的总金额和级别
		OrderContract  o= orderContractService.selectByPrimaryKey(id);
		Sale sale1 = saleService.selectByPrimaryKey(o.getSaleId());
		BigDecimal totalSale1 = sale1.getTotalSale();
		totalSale1 = totalSale1.subtract(orderPay);
		if(totalSale1.compareTo(new BigDecimal(0))<0) {
			totalSale1 = new BigDecimal(0);
		}
		sale1.setTotalSale(totalSale1);
		sale1.setLevel(saleService.getSaleLevel(saleId));
		saleService.update(sale1);
		
		// 更新销售老师销售总金额和级别
		Sale sale = saleService.selectByPrimaryKey(saleId);
		BigDecimal totalSale = sale.getTotalSale();
		totalSale = totalSale.add(orderPay);
		sale.setTotalSale(totalSale);
		int level = saleService.getSaleLevel(saleId);
		sale.setLevel(level);
		saleService.update(sale);

		// 记录日志
		OrderLog log1 = new OrderLog();
		log1.setOrderId(orderId);
		log1.setOrderNo(orderNo);
		log1.setLogType("order_contract");
		log1.setLogName("修改合同");
		log1.setActionId(actionId);
		log1.setActionName(actionName);
		log1.setRemark("修改合同信息");
		log1.setAddTime(TimeStampUtil.getNowSecond().intValue());
		orderLogService.insert(log1);

		// 更新orderResume表

		// 更新jhj-provider-resume 的状态
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("resumeNo", resumeNo);
		params.put("status", "0");
		params.put("actionId", String.valueOf(actionId));
		params.put("actionName", actionName);
		params.put("actionMobile", actionMobile);
		params = JhjSignUtils.getSignParams(params);
		
		String appkey = JhjSignConfig.appkey;
		String oncestr = params.get("oncestr").toString();
		String sign = params.get("sign").toString();
		
		resumeClient.setStatus(resumeNo, 0, actionId, actionName, actionMobile, appkey, oncestr, sign);
		
		return result;
	}

	/**
	 * 合同记录下载
	 * 
	 * @param orderNo
	 *            订单编号
	 * @return list
	 * @throws MalformedURLException
	 * 
	 */
	@RequestMapping(value = "/api/bm/order/contract/downLoad.json", method = RequestMethod.GET)
	public void downContract(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("orderId") Integer orderId) throws MalformedURLException {

	}

}
